import fenpeiForm from "../form/fenpei.vue";
import applyForm from "../form/applyForm.vue";
import guidelineForm from "../form/guidelineForm.vue";
import orderDetailForm from "../form/orderDetail.vue";
import {message} from "@/utils/message";
import {ElMessage} from 'element-plus'
import {hasPerms} from "@/utils/auth";
import {getOrderList, getOrderSta, getOrderConfig, getOrdersSynchronous} from "@/api/system";
import {createVNode, h, onMounted, reactive, ref, type Ref, toRaw, computed} from "vue";
import type {FormItemProps} from "../utils/types";
import {copyTextToClipboard, deviceDetection, getKeyList, storageLocal} from "@pureadmin/utils";
import type {PaginationProps} from "@pureadmin/table";
import {addDrawer} from "@/components/ReDrawer/index";
import {addDialog, closeDialog} from "@/components/ReDialog/index";
import {useRoute} from 'vue-router';
import {applyController, getSalesList} from "@/api/crm";
import {CopyDocument} from '@element-plus/icons-vue'
import {transformI18n} from "@/plugins/i18n";
import {utils, writeFile} from "xlsx";
import EditableCell from "@/components/EditableCell.vue";

export function useOrders(tableRef: Ref) {
  const route = useRoute();
  const form = reactive({
    name: "",
    team_id: "",
    fugou: "",
    tab_id: "0",//diy_status
    search_field: "order_number", search: '', order: 'desc', sortField: 'default_sort',
    status: null
  });

  const formRef = ref();
  const shopList = ref([]);
  const sta_order_statc = ref({gj: [], zt: []});
  const columnsKey = ref('');
  const dataList = ref([]);
  const loading = ref(true);
  const activeStatus = ref(route.query?.order_status || '-1')
  const selectedNum = ref(0);
  const statistics = ref([]);
  const alloStatus = ref([]);
  const teamList = ref([]);
  const financial_status_arr = ref([]);
  const salesman_arr = ref([]);
  const state_arr = ref([]);
  const shop_group_list_arr = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0, pageSize: storageLocal().getItem('order_pageSize') || 12, pageSizes: [10, 20, 40, 60, 100],
    currentPage: 1, background: true
  });
  const tags = [
    {color: '#ccc', value: '',name: '未选择'},{color: '#f38080', value: '无效账号', name: '无效账号'}, {color: '#3eb5b5', value: '已添加WA', name: '已添加WA'}
  ]
  const tags2 = [
    {color: '#ccc', value: '',name: '未选择'},{color: '#49af49', value: '已发短信', name: '已发短信'}, {color: '#b1b10f', value: '已发邮件', name: '已发邮件'}
  ]
  const tags4 = [
    {color: '#ccc', value: '',name: '未选择'}, {color: '#49af49', value: '已回复', name: '已回复'}, {color: '#b1b10f', value: '未回复', name: '未回复'}
  ]


  const tags3 = ref([])
  const tags5 = ref([])
  const tags6 = ref([])

  function onInputChange(row,field='') {
    row.isModified = true; // 手动标记为已修改
    //相同邮箱改了一个，其它的也要改
    if(field=='diy_sales'){
      dataList.value = dataList.value.map(order => {
        // 比较小写后的邮箱是否匹配目标邮箱（不区分大小写）
        if (order.customer_email.toLowerCase() === row.customer_email.toLowerCase()) {
          // 匹配则返回新对象，修改diy_sales为新的
          return { ...order, diy_sales: row.diy_sales };
        }
        // 不匹配则返回原对象
        return order;
      });
    }
  }

  const dataField = ref(['勾选列', '展开', '订单编号']);
  const db_fields_all = ref(['勾选列', '展开', '订单编号']);
  const utmOptions = [
    {label: 'Facebook', value: 'facebook', style: ''},
    {label: 'Instagram', value: 'instagram', style: ''},
    {label: 'Tiktok', value: 'tiktok', style: ''},
    {label: 'Youtube', value: 'youtube', style: ''},
    {label: 'nm30.abv.bg', value: 'nm30.abv.bg', style: ''}
  ];
  const perms = {
    allo: hasPerms('order:btn:allo'),//分配权限
    genjin: hasPerms('order:btn:genjin'),//跟进权限
    caller: hasPerms('button:order:caller')//电联权限
  };

  const columns = ref([
    {label: "勾选列", type: "selection", width: 50, disabled: true, fixed: true},
    {label: "订单编号", prop: "order_number", width: 150, align: "left", disabled: true, fixed: true, className: 'orderNumber',
      cellRenderer: ({row, index}) => (
        <>
          {index + 1}
          <el-icon v-copy:click={row.order_number}><CopyDocument/></el-icon>
          <el-text type={row.diy_fugou == '1' ? "success" : (row.diy_fugou == '2' ? "warning" : "primary")} size="small"
                   data-id={row.order_number} onClick={seeOrderDetail}>{row.order_number}</el-text>
          {row.isModified == true && (perms.allo || perms.genjin) ? (
            <>
              <br/> <el-button type="primary" size="small" onClick={() => onSaveOrder(row)} style="padding:0 10px;margin-top:-15px;">保存</el-button>
            </>
          ) : null}
        </>
      ),
    },
    {
      label: "业务员", prop: "diy_sales_name", width: 130, cellRenderer: ({row}) => {
        const options = salesman_arr.value.map(item => ({
          label: (Array.isArray(item?.site_group) && item?.site_group[0] > 0 ? (item?.sales_group) : (item.dept?.name)) + '-' + item.username,
          value: item.id,
          style: 'background:' + (item.setting?.bgcolor || '') + ';color:' + (item.setting?.color || '')
        }));
        const found = salesman_arr.value.find(x => x.id == row.diy_sales);
        const displayText = found ? (found.dept?.name + '-' + found.username) : '请分配';
        const displayStyle = found ? ('background:' + (found.setting?.bgcolor || '') + ';color:' + (found.setting?.color || '')) : '';
        return h(EditableCell, {
          modelValue: row.diy_sales,
          "onUpdate:modelValue": (val) => {
            row.diy_sales = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.allo,
          onChange: () => onInputChange(row,'diy_sales')
        });
      }
    },
    { label: "跟进状态", prop: "diy_status_text", width: 75},
    { label: "UTM来源", prop: "utm_source", width: 100, cellRenderer: ({row}) => {
        const found = utmOptions.find(x => x.value == row.utm_source);
        const displayText = found ? found.label : '';
        const displayStyle = '';
        return h(EditableCell, {
          modelValue: row.utm_source,
          "onUpdate:modelValue": (val) => {
            row.utm_source = val;
          },
          options: utmOptions,
          displayText,
          displayStyle,
          placeholder: '请选择',
          disabled: !perms.genjin,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "账号状态", prop: "diy_tags", width: 110,
      cellRenderer: ({row}) => {
        const options = tags.map(item => ({
          label: item.name,
          value: item.value,
          style: 'background:' + (item.color || '') + ';color:#fff'
        }));
        const found = tags.find(x => x.value == row.diy_tags);
        const displayText = found ? found.name : '';
        const displayStyle = found ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags,
          "onUpdate:modelValue": (val) => {
            row.diy_tags = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.genjin,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "是否联系", prop: "diy_tags2", width: 110,
      cellRenderer: ({row}) => {
        const options = tags2.map(item => ({
          label: item.name,
          value: item.value,
          style: 'background:' + (item.color || '') + ';color:#fff'
        }));
        const found = tags2.find(x => x.value == row.diy_tags2);
        const displayText = found ? found.name : '';
        const displayStyle = found ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags2,
          "onUpdate:modelValue": (val) => {
            row.diy_tags2 = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.genjin,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "是否成交", prop: "diy_tags3", width: 110,
      cellRenderer: ({row}) => {
        const options = tags3.value.map(item => ({
          label: item.name,
          value: item.value,
          style: item.value > 0 ? 'background:' + (item.color || '') + ';color:#fff' : ''
        }));
        const found = tags3.value.find(x => x.value == row.diy_tags3);
        const displayText = found ? found.name : '';
        const displayStyle = found && found.value > 0 ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags3,
          "onUpdate:modelValue": (val) => {
            row.diy_tags3 = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.genjin,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "是否回复", prop: "diy_tags4", width: 110,
      cellRenderer: ({row}) => {
        const options = tags4.map(item => ({
          label: item.name,
          value: item.value,
          style: 'background:' + (item.color || '') + ';color:#fff'
        }));
        const found = tags4.find(x => x.value == row.diy_tags4);
        const displayText = found ? found.name : '';
        const displayStyle = found ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags4,
          "onUpdate:modelValue": (val) => {
            row.diy_tags4 = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.caller,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "电联情况", prop: "diy_tags5", width: 110,
      cellRenderer: ({row}) => {
        const options = tags5.value.map(item => ({
          label: item.name,
          value: item.value,
          style: 'background:' + (item.color || '') + ';color:#fff'
        }));
        const found = tags5.value.find(x => x.value == row.diy_tags5);
        const displayText = found ? found.name : '';
        const displayStyle = found ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags5,
          "onUpdate:modelValue": (val) => {
            row.diy_tags5 = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.caller,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "物流跟进状态", prop: "diy_tags6", width: 130,
      cellRenderer: ({row}) => {
        const options = tags6.value.map(item => ({
          label: item.name,
          value: item.value,
          style: 'background:' + (item.color || '') + ';color:#fff'
        }));
        const found = tags6.value.find(x => x.value == row.diy_tags6);
        const displayText = found ? found.name : '';
        const displayStyle = found ? ('background:' + (found.color || '') + ';color:#fff') : '';
        return h(EditableCell, {
          modelValue: row.diy_tags6,
          "onUpdate:modelValue": (val) => {
            row.diy_tags6 = val;
          },
          options,
          displayText,
          displayStyle,
          disabled: !perms.genjin,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "电联跟进人", prop: "caller_user", width: 110, cellRenderer: ({row}) => {
        const options = salesman_arr.value.filter(x => x.site_group == -4).map(item => ({
          label: (Array.isArray(item?.site_group) && item?.site_group[0] > 0 ? (item?.sales_group[0]) : (item.dept?.name)) + '-' + item.username,
          value: item.id,
          style: 'background:' + (item.setting?.bgcolor || '') + ';color:' + (item.setting?.color || '')
        }));
        const found = salesman_arr.value.find(x => x.id == row.caller_user);
        const displayText = found ? ((Array.isArray(found?.site_group) && found?.site_group[0] > 0 ? (found?.sales_group[0]) : (found.dept?.name)) + '-' + found.username) : '';
        const displayStyle = found ? ('background:' + (found.setting?.bgcolor || '') + ';color:' + (found.setting?.color || '')) : '';
        return h(EditableCell, {
          modelValue: row.caller_user,
          "onUpdate:modelValue": (val) => {
            row.caller_user = val;
          },
          options,
          displayText,
          displayStyle,
          placeholder: '请选择',
          disabled: !perms.caller,
          onChange: () => onInputChange(row)
        });
      }
    },
    {
      label: "电联时间", prop: "caller_at", width: 130, cellRenderer: ({row, index}) => (
        <el-date-picker size="small" style="width:110px;" prefix-icon={""} placeholder="电联时间" class="no-icon" v-model={row.caller_at} disabled={!perms.caller} onChange={() => onInputChange(row)}>
        </el-date-picker>
      )
    },
    {
      label: "跟进记录", prop: "diy_remark", width: 200, cellRenderer: ({row, index}) => (
        <el-input v-model={row.diy_remark} type="textarea" row="1" style="font-size: 12px; line-height: 0.75;"
                  disabled={!perms.genjin && !perms.caller} onChange={() => onInputChange(row)}/>
      )
    },
    {label: "店铺", prop: "shop_name", width: 120, align: "left", showOverflowTooltip: true},
    {label: "交易号", prop: "transaction.transaction_no", minWidth: 180},
    {label: "是否复购", prop: "diy_fugou_text", width: 70},
    {label: "分配时间", prop: "diy_allo_at", width: 130},
    {label: "首购业务员", prop: "diy_sales_first_text", width: 80},
    {label: "网站分组", prop: "diy_group_text", width: 100},
    {label: "支付方式", prop: "payment_method", minWidth: 70,},
    {label: "店铺地址", prop: "store_url", minWidth: 110, showOverflowTooltip: true},
    {label: "订单状态", prop: "status_text", minWidth: 70},
    {label: "付款状态", prop: "financial_status_text", minWidth: 70},//
    {label: "付款时间", prop: "pay_at", minWidth: 220},//
    {label: "发货状态", prop: "fulfillment_status_text", minWidth: 70},//
    {label: "客户信息", minWidth: 120, prop: "customer_name", showOverflowTooltip: true,},
    {label: "来源域名", minWidth: 120, prop: "domain", showOverflowTooltip: true},
    {label: "IP", minWidth: 110, prop: "ip", showOverflowTooltip: true},
    {label: "国家", minWidth: 100, prop: "shipping_address.country_name"},
    {label: "总商品数", minWidth: 100, prop: "total_num"},
    {label: "订单金额", minWidth: 100, prop: "total_price"},
    {label: "报价金额", minWidth: 80, prop: "current_offer_price"},
    {label: "物流支出", minWidth: 80, prop: "current_shipping_price"},
    {label: "物流称重", minWidth: 110, prop: "total_weight"},
    {label: "订单备注", minWidth: 130, prop: "note", showOverflowTooltip: true},
    {label: "商家备注", minWidth: 130, prop: "admin_note", showOverflowTooltip: true},
    {label: "最后物流时间", minWidth: 130, prop: "delivery_at"},
    {label: "国家(英文)", minWidth: 90, prop: "shipping_address.country_name"},
    {label: "币种", minWidth: 60, prop: "currency_code"},
    {label: "最后更新时间", minWidth: 130, prop: "updated_at"},
    {label: "物流方案", minWidth: 130, prop: "shipping_zone_plan_name"},
    {label: "买家省份", minWidth: 80, prop: "shipping_address.province"},
    {label: "买家邮编", minWidth: 80, prop: "shipping_address.zip"},
    {label: "买家电话", minWidth: 105, prop: "shipping_address.phone", sortable: "custom"},
    {label: "买家email", minWidth: 150, prop: "customer_email", showOverflowTooltip: true, sortable: "custom"},
  ]);
  columns.value.forEach(col => col.hide = () => !dataField.value.includes(col.label));

  const searchCondList = ref([])

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  const sortChange = (k: any) => {
    form.sortField = k.prop
    form.order = k.order == 'descending' ? 'desc' : 'asc'
    onlySearch()
  }

  function changeStatus() {

  }

  async function getConfig() {
    const {data} = await getOrderConfig(form); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    columns.value = columns.value.filter(x => data.db_fields_all.includes(x.label));
    dataField.value = data.db_fields;
    db_fields_all.value = data.db_fields_all;


    shopList.value = data.shop_list;
    searchCondList.value = data?.search_cond_arr;
    tags3.value = data?.tag3_arr
    tags5.value = data?.tag5_arr
    tags6.value = data?.tag6_arr
    // teamList.value = data?.team_list;
    alloStatus.value = data?.allo_status_arr;
    financial_status_arr.value = data?.financial_status_arr;
    shop_group_list_arr.value = data?.shop_group_list;
    state_arr.value = data?.state_arr;
  }

  async function onlySearch() {
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    loading.value = true;
    form.diy_remark = '';
    // form.diy_status = '';
    //form.status = '';
    if (form.tab_id == -1) {//未分配
      form.diy_status = '-1';
    } else if (form.tab_id == 1) {//待处理
      form.diy_status = '';
      form.status = '110';
    } else if (form.tab_id == 2) {//弃单
      form.diy_status = '';
      form.status = '100';
    } else if (form.tab_id == 3) {//跟进超时
      form.diy_status = '';
      form.diy_status = '3';
    } else if (form.tab_id == 4) {//店铺轮询引流分配
      form.diy_status = '';
      form.diy_remark = '店铺轮询引流分配';
    } else {
      form.diy_status = '';
      form.status = '';
    }
    const {data} = await getOrderList(form); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    dataList.value = data.data;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;


    setTimeout(() => {
      loading.value = false;
    }, 300);
  }

  async function onSearch() {
    onlySearch();
    getSta();
    expandact();
  }

  const getSalemanList = async function (page = 1, limit = 1000) {
    const {data} = await getSalesList({page, limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
    if (data?.me?.site_group != -2 || data?.me?.site_group != -3) {//非组长和业务员时，应该可以看到组列表
      const dept = data?.data.filter(x => x.dept?.parent_id == 4).map(x => x.dept);
      teamList.value = [...new Map(dept.map(item => [item?.id, item])).values()];//去重
    }

  }


  async function setBatchSearch() {
    // 兼容 Windows (\r\n) 和 Linux (\n)
    const lineBreak = navigator.platform.includes('Win') ? '\r\n' : '\n';
    // 将指定分隔符（如逗号）转换为换行符，并清理多余空格
    // form.search = form.search.replace(/[,;]\s*/g, lineBreak).trim();
    const SearchTxt = ref('')
    const SearchArr = ref([])
    if (form.search_field == 'j.shipping_address.country_name') {
      if (!Array.isArray(form.search)) SearchArr.value = form.search.split(";")
    } else {
      SearchTxt.value = form.search.replace(/[,;]\s*/g, lineBreak).trim();
    }

    const handleCheckChange = (data, checked, indeterminate) => {
      if (checked) {
        SearchArr.value.push(data.label_en)
      } else {
        const index = SearchArr.value.indexOf(data.label_en);
        if (index !== -1) {
          SearchArr.value.splice(index, 1); // 从索引位置删除1个元素
        }
      }
    }

    addDialog({
      width: "40%",
      title: "设置批量查询",
      contentRenderer: ({index}) => (
        <el-form size="small">
          <el-form-item label="查询条件">
            <el-radio-group v-model={form.search_field}>
              {() => searchCondList.value.map(item => (
                <el-radio key={item.value} value={item.value} disabled={!item.value}>
                  按{item.name}
                </el-radio>
              ))}
            </el-radio-group>
          </el-form-item>
          <el-form-item label="查询内容">
            {form.search_field != 'j.shipping_address.country_name' ?
              <el-input v-model={SearchTxt.value} rows={10} type="textarea" placeholder="多个回车换行"/> :
              <el-tree style="max-width: 500px" data={state_arr.value} show-checkbox label="label_cn"
                       props={{class: 'is-penultimate'}}
                       onCheckChange={handleCheckChange} node-key="label_en" default-expand-all
                       default-checked-keys={SearchArr}/>
            }
          </el-form-item>
        </el-form>
      ),
      closeCallBack: ({options, args}) => {
        if (form.search_field != 'j.shipping_address.country_name') {
          form.search = SearchTxt.value.split(/\r?\n/).filter(Boolean).join(';');
        } else {
          form.search = SearchArr.value.join(';');
        }
      }
    });

  }

  function openDialog() {
  }


  function handleSizeChange(val: number) {
    pagination.pageSize = val
    storageLocal().setItem('order_pageSize', val)
    onlySearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onlySearch()
  }

  function getSta() {
    loading.value = true;
    getOrderSta(form).then(res => {
      if (res.code === 0) {
        sta_order_statc.value = res.data;
        setTimeout(() => {
          loading.value = false;
        }, 500);
      }
    })

    // const { data } = getOrderSta(form);
    // sta_order_statc.value = data;
    // setTimeout(() => {
    //   loading.value = false;
    // }, 500);
  }

  onMounted(async () => {
    getConfig();
    onSearch();
    getSalemanList();
  });

  const export_data = async () => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const {data} = await getOrderList(toRaw({
      ...form,
      page: pagination.currentPage,
      export: 1,
      limit: 1000,
      'order_number': getKeyList(curSelected, "order_number").join(',')
    }), 'get');
    const res = data.field
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `订单列表${new Date().toISOString()}.xlsx`);
  }
  const copy_order = async (field = 'order_number') => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const success = copyTextToClipboard(getKeyList(curSelected, field).join("\r\n"));
    success
      ? message("复制成功", {type: "success"})
      : message("复制失败", {type: "error"});
  }

  function seeOrderDetail(e) {
    if (!hasPerms('order:btn:detail')) return message('无权限查看详情')
    // if(roles[0]=='elisor')return message('行政无权限查看订单详情')
    let orderId = e.target.getAttribute('data-id')
    let row1 = ref({})
    row1.value = dataList.value.find(x => x.order_number == orderId)
    addDrawer({
      size: '60%',
      title: `订单详情:${orderId}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: true,
      headerStyle: `{ marginBottom: '0px' }`,
      contentRenderer: () =>
        createVNode(orderDetailForm, {
          formInline: row1.value
        }),
    });
  }

  function onSaveOrder(row) {
    delete row.shipping_address;
    delete row.items;
    delete row.logs;
    getOrderList(row, "post").then(res => {
      if (res.code === 0) {
        row.isModified = false;
        ElMessage({message: `修改成功`, type: "success"})
        onlySearch();
      } else {
        message(`失败，原因：${res.message}`, {type: "error"});
      }
    })
  }

  //批量保存所有的修改的订单
  function onSaveOrderBatch() {
    dataList.value.filter(x => x.isModified == true).map(x => onSaveOrder(x));
  }


  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  function modal_action(modal_type = 1, row?: FormItemProps) {
    let title, editForm;
    let row1 = row
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    title = '转分配';
    editForm = fenpeiForm;
    row1 = ref({diy_sales: "", remark: "", selectOrders: curSelected, sales: salesman_arr.value})

    addDrawer({
      size: modal_type < 3 ? "60%" : '40%',
      title: `${title}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      contentRenderer: () => h(editForm, {ref: formRef, formInline: row1.value}),
      beforeSure: (done, {options}) => {
        const FormRef = formRef.value.getRef();
        // const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            if (row1.value.selectOrders.length < 1) {
              return message(`未选中订单`, {type: "error"});
            } else if (row1.value.diy_sales < 1) {
              return message(`未选中业务员`, {type: "error"});
            }
            getOrderList(row1.value, "post").then(res => {
              if (res.code === 0) {
                done();
                if (res.data.filter(x => x.id > 0).length > 0) ElMessage({
                  message: `订单${res.data.filter(x => x.id > 0).map(x => x.order_number).join(';')}成功分配`,
                  type: "success"
                })
                if (res.data.filter(x => x.id == 0).length > 0) ElMessage({
                  message: `订单${res.data.filter(x => x.id == 0).map(x => ('订单' + x.order_number + '分配失败,失败原因' + x.message)).join(';')}`,
                  type: "error"
                })
              } else {
                message(`失败，原因：${res.message}`, {type: "error"});
              }
            })
            pagination.currentPage = 1;
            onlySearch();
          }
        });
      },
      closeCallBack: ({options, args}) => {
        if (args?.command === "cancel") {
          message(`取消操作`, {type: "warning"});
          onSelectionCancel()
        } else if (args?.command === "sure") {
          onSelectionCancel()
        } else {

        }
      }
    });
  }

  //动态控制展开或折叠
  const expandedRowKeys = ref([])

  function expandact() {
    const type = storageLocal().getItem("expand_orders");
    if (type) {
      expandedRowKeys.value = dataList.value.map(row => row.platformOrderId)
    } else {
      expandedRowKeys.value = []
    }
  }

  const expandStatus = storageLocal().getItem("expand_orders") || false


  //待补参考
  function guideline() {
    addDialog({
      title: `待补参考`,
      props: {
        formInline: JSON.parse(JSON.stringify({})),//type1编辑，2浏览
      },
      width: "45%",
      draggable: true,
      hideFooter: false,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(guidelineForm, {ref: formRef, formInline: null}),
    });
  }

  const ordersSynchronous = async () => {
    await getOrdersSynchronous();
  }

  function addApplyLog() {
    function saveVisitLog(options, index) {
      const FormRef = formRef.value.getRef();
      const curData = options.props.formInline;
      FormRef.validate(valid => {
        if (valid) {
          applyController(curData, "post").then(res => {
            if (res.code === 0) {
              message(`您已成功提交的这条订单认领数据`, {type: "success"});
              closeDialog(options, index);
              onSearch()
            } else {
              message(`订单认领失败，原因：${res.message}`, {type: "error"});
            }
          })
        }
      });
    }

    addDialog({
      title: `新增订单认领`,
      props: {
        formInline: JSON.parse(JSON.stringify({})),//type1编辑，2浏览
      },
      width: "40%",
      draggable: true,
      hideFooter: false,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(applyForm, {ref: formRef, formInline: null}),
      footerButtons: [
        {
          label: "取消", size: "small", type: "info", btnClick: ({dialog: {options, index}, button}) => {
            closeDialog(options, index);
          }
        },

        {
          label: "提交", size: "small", type: "success",
          btnClick: ({dialog: {options, index}, button}) => {
            saveVisitLog(options, index)
          }
        }
      ],
    });
  }

  return {
    form, expandedRowKeys, loading, columnsKey, addApplyLog, copy_order,
    columns, expandStatus, dataList, alloStatus, financial_status_arr, teamList,
    shopList, sta_order_statc, salesman_arr, shop_group_list_arr,
    modal_action, db_fields_all, onSaveOrderBatch, tags5, tags6, export_data,
    onSearch, activeStatus, selectedNum, onSelectionCancel, sortChange,
    resetForm, openDialog, pagination, changeStatus, onlySearch, guideline,
    handleSelectionChange, searchCondList, setBatchSearch, tags3, tags, tags2,
    handleSizeChange, statistics, handleCurrentChange, ordersSynchronous
  };
}
